package com.example.service.impl;

import com.example.constant.EnumConstant;
import com.example.exception.BusinessException;
import com.example.mapper.RegionMapper;
import com.example.mapper.UserMapper;
import com.example.model.pojo.Person;
import com.example.model.vo.ResultVO;
import com.example.service.AiService;
import com.example.utils.WeBASEUtils;
import io.github.pigmesh.ai.deepseek.core.DeepSeekClient;
import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionRequest;
import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import reactor.core.publisher.Flux;
import reactor.util.retry.Retry;
import com.example.model.vo.QueryOpenAreaVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.alibaba.fastjson.JSON;

import javax.annotation.Resource;
import java.util.List;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author zhexueqi
 * @ClassName AiServiceImpl
 * @since 2024/4/12    16:24
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AiServiceImpl implements AiService {

    final WeBASEUtils weBASEUtils;

    @Autowired
    private DeepSeekClient deepSeekClient;
    @Autowired
    private RegionMapper regionMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    public Flux<ChatCompletionResponse> analyzePolicyRecommendation(String policyData, String personData) {
        final String prompt =
            "请分析以下养老保险政策数据和用户信息，提供个性化的政策建议：" +
            "政策数据：" + policyData +
            "用户信息：" + personData +
            "请提供详细的分析报告，必须严格按照以下JSON格式返回：" +
            "{" +
            "  \"analysis_result\": {" +
            "    \"summary\": \"总体分析概述...\"," +
            "    \"policy_match\": {" +
            "      \"best_match\": \"最佳匹配的政策名称\"," +
            "      \"match_reason\": \"匹配原因说明\"" +
            "    }," +
            "    \"key_insights\": [" +
            "      \"关键建议1\"," +
            "      \"关键建议2\"" +
            "    ]," +
            "    \"risk_analysis\": {" +
            "      \"level\": \"低/中/高\"," +
            "      \"factors\": [\"风险因素1\", \"风险因素2\"]" +
            "    }" +
            "  }" +
            "}";

        return deepSeekClient.chatFluxCompletion(prompt)
            .timeout(Duration.ofSeconds(30))
            .doOnError(e -> log.error("AI policy analysis error", e))
            .retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
            .onErrorResume(e -> Flux.error(new BusinessException(ResultVO.AI_ERROR)));
    }

    @Override
    public String analyzeAi(String dataType, String startDate, String endDate, String dimensions, String prompt) {

        prompt  = getPrompt(dataType, startDate, endDate, dimensions, prompt);

        ChatCompletionRequest request = ChatCompletionRequest.builder()
                // 根据渠道模型名称动态修改这个参数
//                .model("deepseek/deepseek-v3/community")
                .addUserMessage(prompt).build();
        ChatCompletionResponse execute = deepSeekClient.chatCompletion(request).execute();
        String content = execute.content();
        log.info("content:{}", content);
        return content;
    }

    @Override
    public Flux<ChatCompletionResponse> chatWithAi(@RequestParam String dataType,
                                                   @RequestParam String startDate,
                                                   @RequestParam String endDate,
                                                   @RequestParam String dimensions,
                                                    String prompt
    ) {
        prompt = getPrompt(dataType, startDate, endDate, dimensions, prompt);

        ChatCompletionRequest request = ChatCompletionRequest.builder()
                // 模型选择，支持 DEEPSEEK_CHAT、DEEPSEEK_REASONER 等
//                .model(ChatCompletionModel.DEEPSEEK_CHAT)
                // 添加用户消息
                .addUserMessage(prompt)
                // 设置最大生成 token 数，默认 2048
                .maxTokens(1000)
                .build();

        return deepSeekClient.chatFluxCompletion(request);

//    return deepSeekClient.chatFluxCompletion(prompt)
//        .timeout(Duration.ofSeconds(30))
//        .doOnError(e -> log.error("AI chat error", e))
//        .retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
//        .onErrorResume(e -> Flux.error(new BusinessException(ResultVO.AI_ERROR)));
    }

    /**
     * 拼接条件，返回prompt
     */
    private String getPrompt(String dataType, String startDate, String endDate, String dimensions, String prompt) {
        // 解析dimensions参数
        List<String> dimensionList = dimensions != null && !dimensions.isEmpty() ?
                Arrays.asList(dimensions.split(",")) : new ArrayList<>();

        // 准备数据JSON字符串
        StringBuilder dataJsonBuilder = new StringBuilder();

        // 如果包含region维度，查询区域数据
        if (dimensionList.contains("region")) {
            List<QueryOpenAreaVO> areaData = regionMapper.selectAllRegions();
            dataJsonBuilder.append("\"region_data\":").append(JSON.toJSONString(areaData)).append(",");
        }

        // 构建用户查询条件
        QueryWrapper<Person> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_type", EnumConstant.EMPLOYEE);
        if (!dimensionList.isEmpty()) {
            // 如果有指定维度，只查询指定字段
            List<String> selectColumns = new ArrayList<>();
            if (dimensionList.contains("age")) {
                selectColumns.add("age");
            }
            if (dimensionList.contains("gender")) {
                selectColumns.add("sex");
            }
            if (!selectColumns.isEmpty()) {
                userQueryWrapper.select(String.join(",", selectColumns));
            }
        }
        List<Person> userData = userMapper.selectList(userQueryWrapper);
        dataJsonBuilder.append("\"user_data\":").append(JSON.toJSONString(userData));

        // 构建完整的数据JSON
        String dataJson = dataJsonBuilder.length() == 0 ? "{}" : ("{" + dataJsonBuilder.toString() + "}");
        log.debug("构造的dataJson内容: {}", dataJson); // 新增日志输出dataJson内容
    
        // 拼接prompt
        prompt = prompt + "数据：" + dataJson + "请根据以上数据，回答用户问题：" + prompt;
        return prompt;
    }



    @Override
    public String chatWithAI(String prompt){
        ChatCompletionRequest request = ChatCompletionRequest.builder()
                .addUserMessage(prompt).build();
        ChatCompletionResponse execute = deepSeekClient.chatCompletion(request).execute();

        return execute.content();
    }
}